解釋JAVA程式碼~到六成啦~時間好快![]()
今天要說到的是Lambda減少程式碼,但是功能沒有減少,自帶return,
但是{} 結束還是要有;
->操作符號:Lambda Operator
https://openhome.cc/zh-tw/java/lambda/functional-interface/
程式碼
package FunctionalInterface;
public class Lambda01 {
public static void main(String[] args) {
//Lambda 無參數
System.out.println("\nLambda 無參數");
Pen p1 = ()-> System.out.println("p1");
p1.draw();
Pen1 p2 = ()->{
int price = 85;
return price;
};
System.out.println(p2.draw());
//Lambda 1參數
System.out.println("\nLambda 1參數");
Pen2 p22 = x -> {
x += 100;
System.out.println(x);
};
p22.draw2(56);
Pen21 p221 = (int x)-> x+=100;
System.out.println(p221.draw2(56));
//Lambda 多參數
System.out.println("\nLambda 多參數");
Pen3 p33 = (a,b)->System.out.println(a+b);
p33.draw3(10, 20);
Pen31 p331 = (int a, int b)-> a+b;
System.out.println(p331.draw3(10, 20));
}
}
//--------------------------
@FunctionalInterface
interface Pen{
void draw();
}
@FunctionalInterface
interface Pen1{
int draw();
}
//-------------------------
@FunctionalInterface
interface Pen2{
void draw2(int i);
}
@FunctionalInterface
interface Pen21{
int draw2(int i);
}
//---------------------
@FunctionalInterface
interface Pen3{
void draw3(int i,int j);
}
@FunctionalInterface
interface Pen31{
int draw3(int i,int j);
}
顯示
這段Java程式碼示範了如何使用Lambda表達式(Lambda expressions)來實現不同類型的函數式接口(Functional Interface)。以下是程式碼的解釋:
定義了幾個不同的函數式介面(Functional Interface),每個介面都有不同數量的參數和返回值類型。
使用Lambda表達式實現這些介面的方法:
Pen 介面具有無參數方法 draw,第一個Lambda示例 p1 實現了這個方法,它只是印出 "p1"。Pen1 介面具有返回整數的方法 draw,第二個Lambda示例 p2 實現了這個方法,計算並返回一個整數值 85。Pen2 介面具有一個整數參數的方法 draw2,Lambda示例 p22 實現了這個方法,將參數增加 100 並印出結果。Pen21 介面也具有一個整數參數的方法 draw2,Lambda示例 p221 實現了這個方法,同樣將參數增加 100,但這次返回結果而不是印出。Pen3 介面具有兩個整數參數的方法 draw3,Lambda示例 p33 實現了這個方法,它印出兩個參數的和。Pen31 介面也具有兩個整數參數的方法 draw3,Lambda示例 p331 實現了這個方法,返回兩個參數的和。在每個Lambda表達式中,你可以看到使用箭頭 -> 將參數列表和方法主體分開,並根據介面方法的要求提供實現。
總結來說,這段程式碼展示了如何使用Lambda表達式來實現函數式介面的方法,這種方式更簡潔且易讀,特別適合於處理簡單的函數性任務。
![]()
謝謝收看![]()